{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 填充和跨步\n",
    "\n",
    ":label:`sec_padding`\n",
    "\n",
    "\n",
    "在上一个示例中，我们的输入的高度和宽度均为 $3$\n",
    "我们的卷积内核的高度和宽度都是 $2$,\n",
    "生成维度为 $2\\times2$ 的输出表示。\n",
    "通常，假设输入形状为 $n_h\\times n_w$\n",
    "卷积核窗口的形状是 $k_h\\times k_w$，\n",
    "然后输出形状将是\n",
    "\n",
    "$$(n_h-k_h+1) \\times (n_w-k_w+1).$$\n",
    "\n",
    "因此，卷积层的输出形状\n",
    "由输入的形状决定\n",
    "以及卷积核窗口的形状。\n",
    "\n",
    "在一些情况下，我们结合了技术，\n",
    "包括填充和跨步卷积，\n",
    "这会影响输出的大小。\n",
    "作为动机，请注意，由于内核\n",
    "宽度和高度大于$1$，\n",
    "在应用多次连续卷积之后，\n",
    "我们最终往往会得到\n",
    "远小于我们的输入。\n",
    "如果我们从$240 \\times 240$的像素图像开始，\n",
    "$10$层的$5 \\times 5$卷积\n",
    "将图像减少到$200 \\times 200$像素，\n",
    "从图像中切下 $30 \\%$并使用它\n",
    "删除任何有趣的信息\n",
    "在原始图像的边界上。\n",
    "*Padding*是处理此问题最常用的工具。\n",
    "\n",
    "在其他情况下，我们可能希望大幅降低维度，\n",
    "例如，如果我们发现原始输入分辨率很难处理。\n",
    "*跨步卷积*是一种流行的技术，可以在这些情况下有所帮助。\n",
    "\n",
    "## 填充\n",
    "\n",
    "如上所述，应用卷积层时有一个棘手的问题\n",
    "我们往往会丢失图像周边的像素。\n",
    "因为我们通常使用小内核，\n",
    "对于任何给定的卷积，\n",
    "我们可能只会损失几个像素，\n",
    "但是，当我们申请时，这可以加起来\n",
    "许多连续的卷积层。\n",
    "这个问题的一个简单解决方案\n",
    "就是在输入图像的边界周围添加额外的填充像素，\n",
    "从而增加了图像的有效大小。\n",
    "通常，我们将额外像素的值设置为 $0$。\n",
    "在 :numref:`img_conv_pad`中，我们输入 $3 \\times 3$，\n",
    "将其大小增加到 $5 \\times 5$。\n",
    "相应的输出随后增加到 $4 \\times 4$ 的矩阵。\n",
    "\n",
    "![Two-dimensional cross-correlation with padding. The shaded portions are the input and kernel array elements used by the first output element: $0\\times0+0\\times1+0\\times2+0\\times3=0$. ](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/conv-pad.svg)\n",
    "\n",
    ":label:`img_conv_pad`\n",
    "\n",
    "\n",
    "一般来说，如果我们总共添加 $p_h$ 行填充\n",
    "（大约一半在顶部，一半在底部）\n",
    "以及总共 $p_w$ 列的填充\n",
    "（大约一半在左边，一半在右边），\n",
    "输出形状将为\n",
    "\n",
    "$$(n_h-k_h+p_h+1)\\times(n_w-k_w+p_w+1).$$\n",
    "\n",
    "这意味着输出的高度和宽度\n",
    "将分别增加 $p_h$ 和 $p_w$。\n",
    "\n",
    "在许多情况下，我们会希望设置 $p_h=k_h-1$ 和 $p_w=k_w-1$\n",
    "使输入和输出具有相同的高度和宽度。\n",
    "这将更容易预测每层的输出形状\n",
    "在构建网络时。\n",
    "假设 $k_h$ 在这里，\n",
    "我们将在高度的两侧垫 $p_h/2$ 行。\n",
    "如果 $k_h$ 是奇数，一种可能性是\n",
    "将 $\\lceil p_h/2\\rceil$ 行放在输入的顶部\n",
    "和底部的 $\\lfloor p_h/2\\rfloor$ 行。\n",
    "我们将以相同的方式填充宽度的两侧。\n",
    "\n",
    "卷积神经网络通常使用卷积核\n",
    "具有奇数的高度和宽度值，例如$1$， $3$， $5$， 或 $7$。\n",
    "选择奇数内核大小有好处\n",
    "我们可以保持空间维度\n",
    "在顶部和底部填充相同数量的行，\n",
    "左右两侧的列数相同。\n",
    "\n",
    "此外，这种使用奇数核的做法\n",
    "和填充以精确地保留维度\n",
    "提供文书福利。\n",
    "对于任何二维数组 `X`，\n",
    "当果仁大小为奇数时\n",
    "以及填充行和列的数量\n",
    "各方面都是一样的，\n",
    "产生与输入具有相同高度和宽度的输出，\n",
    "我们知道输出 `Y[i, j]` 是经过计算的\n",
    "通过输入和卷积核的互相关\n",
    "窗口以 `X[i, j]`为中心。\n",
    "\n",
    "在下面的示例中，我们创建一个二维卷积层\n",
    "高度和宽度为 $3$\n",
    "并在所有侧面应用 $1$ 像素的填充物。\n",
    "给定一个高度和宽度为 $8$ 的输入，\n",
    "我们发现输出的高度和宽度也是 $8$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/DataPoints.java\n",
    "%load ../utils/Training.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "NDArray X = manager.randomUniform(0f, 1.0f, new Shape(1, 1, 8, 8));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// 请注意，这里每侧填充1行或1列，因此总共2行或1列\n",
    "// 添加行或列\n",
    "Block block = Conv2d.builder()\n",
    "                .setKernelShape(new Shape(3, 3))\n",
    "                .optPadding(new Shape(1, 1))\n",
    "                .setFilters(1)\n",
    "                .build();\n",
    "\n",
    "TrainingConfig config = new DefaultTrainingConfig(Loss.l2Loss());\n",
    "Model model = Model.newInstance(\"conv2D\");\n",
    "model.setBlock(block);\n",
    "\n",
    "Trainer trainer = model.newTrainer(config);\n",
    "trainer.initialize(X.getShape());\n",
    "\n",
    "NDArray yHat = trainer.forward(new NDList(X)).singletonOrThrow();\n",
    "// 排除我们不感兴趣的前两个维度：批次和\n",
    "// 频道\n",
    "System.out.println(yHat.getShape().slice(2));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When the height and width of the convolution kernel are different,\n",
    "we can make the output and input have the same height and width \n",
    "by setting different padding numbers for height and width."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "2"
    }
   },
   "outputs": [],
   "source": [
    "// 这里，我们使用一个高度为5、宽度为3的卷积核。这个\n",
    "// 高度和宽度两侧的填充号分别为2和1，\n",
    "// 分别\n",
    "\n",
    "block = Conv2d.builder()\n",
    "                .setKernelShape(new Shape(5, 3))\n",
    "                .optPadding(new Shape(2, 1))\n",
    "                .setFilters(1)\n",
    "                .build();\n",
    "\n",
    "model.setBlock(block);\n",
    "\n",
    "trainer = model.newTrainer(config);\n",
    "trainer.initialize(X.getShape());\n",
    "\n",
    "yHat = trainer.forward(new NDList(X)).singletonOrThrow();\n",
    "System.out.println(yHat.getShape().slice(2));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 跨步\n",
    "\n",
    "在计算互相关时，\n",
    "我们从卷积窗口开始\n",
    "在输入数组的左上角，\n",
    "然后将其滑动到所有位置，包括向下和向右。\n",
    "在前面的示例中，我们默认一次滑动一个像素。\n",
    "然而，有时，无论是为了计算效率\n",
    "或者因为我们想减少样本，\n",
    "我们一次移动窗口超过一个像素，\n",
    "跳过中间位置。\n",
    "\n",
    "\n",
    "我们将每张幻灯片的行数和列数称为*跨步*。\n",
    "到目前为止，我们已经使用了1美元的跨步，包括高度和宽度。\n",
    "有时，我们可能需要更大的步幅。\n",
    ":numref:`img_conv_stride` 显示二维互相关运算\n",
    "垂直跨步 $3$ ，水平跨步 $2$ 。\n",
    "我们可以看到，当第一列的第二个元素被输出时，\n",
    "卷积窗口向下滑动三行。\n",
    "卷积窗口向右滑动两列\n",
    "当第一行的第二个元素被输出时。\n",
    "当卷积窗口在输入上向右滑动三列时，\n",
    "没有输出，因为输入元素无法填充窗口\n",
    "（除非我们添加另一列填充）。\n",
    "\n",
    "![Cross-correlation with strides of 3 and 2 for height and width respectively. The shaded portions are the output element and the input and core array elements used in its computation: $0\\times0+0\\times1+1\\times2+2\\times3=8$, $0\\times0+6\\times1+0\\times2+0\\times3=6$. ](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/conv-stride.svg)\n",
    "\n",
    ":label:`img_conv_stride`\n",
    "\n",
    "\n",
    "一般来说，当身高的步幅为$s_h$\n",
    "宽度的步幅为$s_w$，输出形状为\n",
    "\n",
    "$$\\lfloor(n_h-k_h+p_h+s_h)/s_h\\rfloor \\times \\lfloor(n_w-k_w+p_w+s_w)/s_w\\rfloor.$$\n",
    "\n",
    "如果我们设置 $p_h=k_h-1$ 和 $p_w=k_w-1$，\n",
    "然后将输出形状简化为\n",
    "$\\lfloor(n_h+s_h-1)/s_h\\rfloor \\times \\lfloor(n_w+s_w-1)/s_w\\rfloor$.\n",
    "如果输入的高度和宽度\n",
    "可以被高度和宽度上的跨步所分割，\n",
    "然后输出形状将是 $(n_h/s_h) \\times (n_w/s_w)$.\n",
    "\n",
    "下面，我们将高度和宽度的跨步设置为 $2$，\n",
    "从而将输入高度和宽度减半。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "block = Conv2d.builder()\n",
    "                .setKernelShape(new Shape(3, 3))\n",
    "                .optPadding(new Shape(1, 1))\n",
    "                .optStride(new Shape(2,2))\n",
    "                .setFilters(1)\n",
    "                .build();\n",
    "\n",
    "model.setBlock(block);\n",
    "\n",
    "trainer = model.newTrainer(config);\n",
    "trainer.initialize(X.getShape());\n",
    "\n",
    "yHat = trainer.forward(new NDList(X)).singletonOrThrow();\n",
    "System.out.println(yHat.getShape().slice(2));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们将看一个稍微复杂一点的例子。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "3"
    }
   },
   "outputs": [],
   "source": [
    "block = Conv2d.builder()\n",
    "                .setKernelShape(new Shape(3, 5))\n",
    "                .optPadding(new Shape(0, 1))\n",
    "                .optStride(new Shape(3,4))\n",
    "                .setFilters(1)\n",
    "                .build();\n",
    "\n",
    "model.setBlock(block);\n",
    "\n",
    "trainer = model.newTrainer(config);\n",
    "trainer.initialize(X.getShape());\n",
    "\n",
    "yHat = trainer.forward(new NDList(X)).singletonOrThrow();\n",
    "System.out.println(yHat.getShape().slice(2));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了简洁起见，当填充数字\n",
    "在输入的两侧，高度和宽度分别是 $p_h$ 和 $p_w$，我们称之为padding $(p_h, p_w)$。\n",
    "具体来说，当 $p_h = p_w = p$ 时，填充是 $p$。\n",
    "当高度和宽度上的跨步分别为 $s_h$ 和 $s_w$ 时，\n",
    "我们称步幅为 $(s_h, s_w)$。\n",
    "具体来说，当 $s_h = s_w = s$ 时，步幅为 $s$。\n",
    "默认情况下，填充为 $0$ ，步幅为 $1$。\n",
    "实际上，我们很少使用不均匀的跨步或填充，\n",
    "例如，我们通常有 $p_h = p_w$ 和 $s_h = s_w$。\n",
    "\n",
    "## 总结\n",
    "\n",
    "* 填充可以增加输出的高度和宽度。这通常用于使输出与输入具有相同的高度和宽度。\n",
    "* 步幅可以降低输出的分辨率，例如，将输出的高度和宽度降低到输入高度和宽度的 $1/n$（$n$ 是大于 $1$ 的整数）。\n",
    "* 填充和跨步可以有效地调整数据的维度。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 对于本节的最后一个示例，使用形状计算公式计算输出形状，以查看其是否与实验结果一致。\n",
    "1. 在本节的实验中尝试其他填充和跨步组合。\n",
    "1. 对于音频信号，$2$ 的步幅对应什么？\n",
    "1. 大于 $1$ 的步幅有什么计算优势。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
